import time

from webdrivermanager_cn.chrome import ChromeDriverManager
import os
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from spider.config.settings import Account


def update_driver():
    try:
        driver_path = ChromeDriverManager().install()
        print(f"驱动自动安装至:{driver_path}")
    except Exception as e:
        print(f"下载驱动发生错误，请检查防火墙或代理设置！\n如反复失败请手动配置！")


def save_cookie():
    account = Account
    login_url = "https://accounts.pixiv.net/login"
    driver_path = account.driver_path

    os.system(r'start chrome --remote-debugging-port=10086')
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:10086")

    driver = Chrome(service=Service(driver_path), options=options)
    driver.get(login_url)

    cookies = driver.get_cookies()
    time.sleep(5)

    cookie = ""
    for field in cookies:
        cookie += (field["name"] + "=" + field["value"] + "; ")

    with open("../config/cookie.txt", "w", encoding="utf-8") as f:
        f.write(cookie)


def get_cookie(path):
    with open(path, "r", encoding="utf-8") as f:
        cookie = f.read()

    return cookie


if __name__ == "__main__":
    save_cookie()